package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.schedule.dto.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.ProtostuffUtil;
import com.heima.wemedia.service.AutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private IScheduleClient scheduleClient;


    @Autowired
    private AutoScanService autoScanService;

    /**
     * 消费延迟队列中的数据
     */
    //todo
    @Override
    @Scheduled(fixedRate = 1000 * 60)
    @SneakyThrows
    public void pollTask() {
        log.info("延迟队列任务消费，并审核---begin");
        ResponseResult responseResult = scheduleClient.poll();
        if (responseResult == null || responseResult.getCode() != 200){
            log.warn("消费队列任务失败");
            return;
        }
        log.warn("消费队列任务成功");
        String data = JSON.toJSONString(responseResult.getData());
        if (data == null){
            log.warn("没有任务被消费");
            return;
        }
        log.warn("有任务正在被消费");
        Task task = JSON.parseObject(data, Task.class);
        if (task == null){
            log.warn("任务Task为空");
            return;
        }
        log.warn("任务Task不为空");
        byte[] parameters = task.getParameters();
        WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
        try {
            log.info("准备开始自动审核");
            autoScanService.autoScanWmNews(wmNews.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("延迟队列任务消费，并审核---end");
    }
}
